<template>
  <div>
    <el-dialog custom-class="dialog"
               :visible.sync="appsDialogVisible"
               :show-close="false"
               width="960px"
               :before-close="resetDialog">
      <div class="dis_flex">
        <div class="d_left">
          <div style="font-size: 24px;font-weight:600">Create</div>
          <div style="font-size: 24px;font-weight:600;margin-top:8px">Your Own Application!</div>
          <div style="margin-top:70px">
            <div @click="clickHandler(index)"
                 :style="{backgroundColor:index === activeIndex?'#2693FF':''}"
                 v-for="(item,index) in optionList"
                 class="option_item cursor_pointer"
                 :key="item"
                 style="font-size:16px;font-weight:600;margin-bottom:5px">
              <span style="font-weight:400;margin-right:15px"
                    class="cuifont icon_no">
              </span>
              {{item}}
            </div>
          </div>
        </div>
        <div class="d_right flex flex-col"
             v-loading="loading">
          <div style="height:28px;display:flex;justify-content:flex-end;margin-bottom:10px">
            <div class="cursor_pointer bgc_hover"
                 style="width:28px;height:28px;text-align:center;line-height:28px;border-radius:2px"><span style="font-size:14px"
                    class="cuifont icon_help_circle"></span></div>
            <div @click="resetDialog"
                 class="cursor_pointer bgc_hover"
                 style="width:28px;height:28px;margin-left:10px;text-align:center;line-height:33px;border-radius:2px"><span style="font-size:18px"
                    class="el-icon-close"></span></div>
          </div>
          <div style="padding-right:10px"
               ref="rightFlex"
               class="flex-1 overflow-auto">
            <el-form ref="form"
                     :rules="rules"
                     label-position="top"
                     label-width="80px"
                     :model="appInfo">
              <template v-if="activeIndex===0">
                <el-form-item label="Name"
                              prop="name">
                  <el-input v-model="appInfo.name"
                            placeholder="Please Enter"
                            clearable></el-input>
                </el-form-item>
                <el-form-item label="Description">
                  <el-input type="textarea"
                            resize="none"
                            :rows="3"
                            v-model="appInfo.description"
                            placeholder="Please Enter"
                            clearable></el-input>
                </el-form-item>
                <el-form-item label="Help and feedback URL">
                  <el-input v-model="appInfo.instructions"
                            placeholder="Please Enter"
                            clearable></el-input>
                </el-form-item>
                <el-form-item prop="period"
                              :label="$t('custom.dataset.status')">
                  <el-select v-model="appInfo.period"
                             style="width: 100%;"
                             :placeholder="$t('custom.dataset.status')">
                    <el-option v-for="(its, index4) in statusList"
                               :key="index4"
                               :label="its.dictLabel"
                               :value="its.dictValue"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="da"
                              :label="$t('custom.report.da')">
                  <el-select v-model="appInfo.da"
                             clearable
                             filterable
                             :placeholder="$t('custom.report.da')"
                             style="width: 100%;">
                    <el-option v-for="(its, index3) in userList"
                               :key="index3"
                               :label="its.realname"
                               :value="its.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="po"
                              :label="$t('custom.report.po')">
                  <el-select v-model="appInfo.po"
                             clearable
                             filterable
                             :placeholder="$t('custom.report.po')"
                             style="width: 100%;">
                    <el-option v-for="(its, index3) in userList"
                               :key="index3"
                               :label="its.realname"
                               :value="its.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="jiraNumber"
                              :label="$t('custom.reports.jiraNumber')">
                  <el-input v-model="appInfo.jiraNumber"
                            @keyup.enter.native.stop
                            type="text"
                            style="width: 100%"
                            rows="3"
                            :placeholder="$t('custom.reports.jiraNumber')">
                    <JiraNumberLink slot="suffix"
                                    :jiraNumber="appInfo.jiraNumber" />
                  </el-input>
                </el-form-item>
                <el-form-item class="icon"
                              label="Icon"
                              prop="fileInfo">
                  <el-upload class="upload-demo"
                             action=""
                             :auto-upload="false"
                             :show-file-list="false"
                             :on-change='changeUpload'>
                    <div style="display:flex">
                      <div style="width:80px;height:80px;margin-right:10px">
                        <img v-if="!loading"
                             :src="appInfo.picture"
                             style="width:60px;height:60px;margin-top:10px;border-radius:4px"
                             alt="">
                      </div>
                      <div style="height:80px;text-align:left">
                        <div slot="tip"
                             class="el-upload__tip"
                             style="font-size: 12px;color: #808080;line-height: 18px;">120*120px, only supports PNG format, and the file is less than or equal to 5 MB.</div>
                        <el-button size="mini"
                                   type="primary"
                                   style="margin-top:12px">Upload</el-button>
                      </div>
                    </div>
                  </el-upload>
                </el-form-item>
              </template>
              <template v-if="activeIndex === 1">

                <el-form-item>
                  <BPlan ref="b-plan"
                         :product.sync="appInfo.chargebeeItemFamilies"
                         :items.sync="appInfo.chargebeeItemPricesList" />
                </el-form-item>

                <el-form-item label="App">
                  <el-select v-model="appInfo.type"
                             clearable>
                    <el-option v-for="record in appTypes"
                               :label="record.label"
                               :value="record.value"
                               :key="record.value"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="Banner">
                  <ZUpload v-model="appInfo.banner" />
                </el-form-item>
                <el-form-item label="Sort">
                  <el-input-number controls-position="right"
                                   v-model="appInfo.sort" />
                </el-form-item>
                <el-form-item label="Pay Mode">
                  <el-select v-model="appInfo.userLimit">
                    <el-option v-for="item in payMode"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :label="$t('attribute.rules')">
                  <BRules v-model="appInfo.sysPaywallList" />
                </el-form-item>
              </template>
              <template v-if="activeIndex === 2">
                <BConfigResource title="Dashboards"
                                 rTitle="Dashboards"
                                 component="Dashboards"
                                 v-model="dashboards"
                                 isUrl
                                 :resourceType="1"
                                 :resourceMenu="1" />
                <BConfigResource title="Bots"
                                 rTitle="Bots"
                                 component="Bots"
                                 v-model="bots"
                                 :resourceType="2"
                                 :resourceMenu="2" />
                <!-- <BConfigResource title="Datasets"
                                 rTitle="Datasets"
                                 component="Datasets"
                                 v-model="datasets"
                                 :resourceType="4"
                                 :resourceMenu="5" />
                <BConfigResource title="Widgets"
                                 rTitle="Widgets"
                                 component="Widgets"
                                 v-model="widgets"
                                 :resourceType="5"
                                 :resourceMenu="4" /> -->
                <BConfigResource title="Settings"
                                 rTitle="Settings"
                                 component="Settings"
                                 v-model="settings"
                                 isUrl
                                 :resourceType="1"
                                 :resourceMenu="3" />
              </template>
              <template v-if="activeIndex === 3">
                <el-form-item label="Version Number"
                              prop="appVersion">
                  <el-cascader v-model="appInfo.appVersion"
                               separator="."
                               :props="{ expandTrigger: 'hover' }"
                               :options="versionOptions"></el-cascader>
                </el-form-item>
                <el-form-item label="Version Description">
                  <el-input type="textarea"
                            resize="none"
                            :rows="3"
                            v-model="appInfo.upgradeDesc"
                            placeholder="Please Enter"
                            clearable></el-input>
                </el-form-item>
                <div v-if="appInfo.id">
                  <div style="height:40px;border:1px solid #DCDFE6;border-bottom:0;line-height:40px;font-size: 14px;font-weight: 600;color: #404040;padding:0 10px;margin-top:16px">Version History</div>
                  <el-table max-height="240"
                            :show-header="false"
                            :data="versionHistory"
                            style="width: 100%;border:1px solid #DCDFE6">
                    <el-table-column type="expand">
                      <template slot-scope="props">
                        <el-form label-position="left"
                                 inline
                                 class="demo-table-expand">
                          <el-form-item>
                            <span>{{props.row.submitDesc}}</span>
                          </el-form-item>
                        </el-form>
                      </template>
                    </el-table-column>
                    <el-table-column prop="appVersion">
                    </el-table-column>
                    <el-table-column>
                      <template slot-scope="scope">
                        {{formatDate( scope.row.updateTime,'MM/DD/YYYY HH:mm')}}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </template>
            </el-form>
          </div>

          <div class="flex items-center"
               style="margin-top:32px">
            <div v-if="activeIndex!==0"
                 @click="handlePrevious"
                 class="cursor_pointer color_hover"
                 style="font-size: 12px;font-weight:600;color: #BFBFBF;">
              PREVIOUS STEP
            </div>

            <div class="flex-1 text-right">
              <el-button size="mini"
                         v-if="activeIndex!==3"
                         type="primary"
                         :loading="nextLoading"
                         @click="handleNext">{{ $t('custom.next') }}</el-button>
              <el-button size="mini"
                         @click="handleSave"
                         :loading="submitLoading"
                         v-if="activeIndex===3"
                         type="primary">{{ $t('custom.save') }}</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible"
               destroy-on-close
               append-to-body>
      <div class="cropper-content">
        <div class="cropper"
             style="text-align:center">
          <vueCropper ref="cropper"
                      :img="appInfo.file"
                      v-bind="option"></vueCropper>
        </div>
      </div>
      <div slot="footer"
           class="dialog-footer">
        <el-button size="mini"
                   @click="dialogVisible = false">Cancel</el-button>
        <el-button size="mini"
                   type="primary"
                   @click="handleUploadIcon"
                   :loading="iconLoading">Confirm</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import AddBox from './add-box.vue'
import selectList from './select-list.vue'
import AddUrlBox from './add-url-box.vue'
import { GlobalTimeformat } from '@/utils/common'
import JiraNumberLink, { JiraNumberMixin } from '@/components/jira-number-link'

import { appTypes } from '@/components/storybook/settings/chargebee'
import BRules from '@/components/storybook/b-rules/index'
import BConfigResource from '@/components/storybook/b-config-resource/index'
import ZUpload from '@/components/storybook/z-upload/index'
import BPlan from '@/components/storybook/b-charge-catalog/index'
import { groupBy, get } from 'lodash'

const payMode = Object.freeze([
  {
    label: 'Bundle',
    value: 0
  },
  {
    label: 'App/User',
    value: 1
  },
  {
    label: 'BI',
    value: 2
  },
  {
    label: 'Bot/User',
    value: 3
  },
  {
    label: 'Bot Usage Unlimited',
    value: 4
  }
])

const optionList = Object.freeze(['BASIC INFOMATION', 'CONFIG RULES', 'APP DEVELOPMENT', 'APP RELEASE'])
export default {
  components: { BPlan, AddBox, AddUrlBox, selectList, JiraNumberLink, ZUpload, BRules, BConfigResource },
  mixins: [JiraNumberMixin],
  data () {
    const validateStatus = (rule, value, callback) => {
      if (this.$store.state.user.username.includes('mspbots.ai') && !this.appInfo.period) {
        callback(new Error('Please select Status'))
        return
      }
      callback()
    }
    const validateDa = (rule, value, callback) => {
      if (this.$store.state.user.username.includes('mspbots.ai') && !this.appInfo.da) {
        callback(new Error(this.$t('custom.component.gadget.da')))
        return
      }
      callback()
    }
    const validatePo = (rule, value, callback) => {
      if (this.$store.state.user.username.includes('mspbots.ai') && !this.appInfo.po) {
        callback(new Error(this.$t('custom.component.gadget.po')))
        return
      }
      callback()
    }
    const validateJira = async (rule, value, callback) => {
      const isMatchJiraNumber = await this.checkJiraNumber(this.appInfo.jiraNumber)

      if (this.$store.state.user.username.includes('mspbots.ai') && !isMatchJiraNumber) {
        callback(new Error(this.$t('custom.component.gadget.checkNumber')))
        return
      }
      callback()
    }
    return {
      appsDialogVisible: false,

      dialogVisible: false,

      picsList: [],

      option: Object.freeze({
        info: true,
        outputSize: 0.8,
        outputType: 'png',
        canScale: false,
        autoCrop: true,
        autoCropWidth: 120,
        autoCropHeight: 120,
        fixedBox: true,
        fixed: true,
        fixedNumber: [5, 5],
        full: true,
        canMoveBox: true,
        original: false,
        centerBox: true,
        infoTrue: false
      }),
      appInfo: {
        id: '',
        name: '',
        description: '',
        appVersion: '',
        upgradeDesc: '',
        type: 0,
        appResourceList: [],
        da: '',
        po: '',
        jiraNumber: '',
        period: '',

        productId: undefined,
        banner: '',
        sysPaywallList: [],
        userLimit: 0,
        picture: 'https://intoss.mspbots.ai/bots/apps/1506462282715107328.png'
      },
      loading: false,
      plans: [],
      addons: [],
      products: [],
      rules: {
        name: [
          { required: true, message: 'Cannot be empty', trigger: 'blur', pattern: '[^ \x22]+' },
          { min: 3, max: 48, message: 'The length is between 3 and 48 characters', trigger: 'blur' },
          { validator: this.validatePass, trigger: 'blur' }
        ],
        period: [{ validator: validateStatus, trigger: 'change' }],
        da: [{ validator: validateDa, trigger: 'change' }],
        po: [{ validator: validatePo, trigger: 'change' }],
        jiraNumber: [{ validator: validateJira, trigger: 'blur' }],
        appVersion: [
          { type: 'array', required: true, message: 'Cannot be empty', trigger: 'change' }
        ]
      },

      versionHistory: [],
      versionOptions: [],
      resourceMenuValue: '',
      userList: [],
      statusList: [
        { dictLabel: 'Alpha', dictValue: 'Alpha' },
        { dictLabel: 'Beta', dictValue: 'Beta' },
        { dictLabel: 'None', dictValue: 'None' }
      ],

      appTypes,
      dashboards: [],
      bots: [],
      widgets: [],
      settings: [],
      datasets: [],
      iconLoading: false,

      payMode,
      optionList,
      nextLoading: false,
      submitLoading: false,
      activeIndex: 0
    }
  },
  created () {
    this.init()
  },

  watch: {
    activeIndex (val) {
      this.$refs.rightFlex.scrollTop = 0
    }
  },
  methods: {
    async changeRule (rules, rule) {
      if (rule.type === '13' && rule.softwareId) {
        await this.getIntegrationResource(rule.softwareId)
      }
    },
    async getIntegrationResource (code) {
      const { integrationResource } = this.$interface.pay

      const params = {
        code
      }
      let { data: response } = await integrationResource(params)
      if (response.code !== 0) {
        throw response.msg
      }

      this.dashboards = get(response, 'data.reportDTOS', []).filter(i => i.businessType === 'Template' && (i.status === 'Published' || i.status === 'Alpha')).map(i => ({
        resourceId: i.id,
        resourceName: i.name,
        resourceType: 1,
        resourceMenu: 1
      }))
      this.datasets = get(response, 'data.sysDatasetDTOS', []).filter(i => i.businessType === 'Template' && (i.status === 'Published' || i.status === 'Alpha')).map(i => ({
        resourceId: i.id,
        resourceName: i.name,
        resourceType: 4,
        resourceMenu: 5
      }))
      this.widgets = get(response, 'data.sysModelDTOS', []).filter(i => i.businessType === 'Template' && (i.status === 'Published' || i.status === 'Alpha')).map(i => ({
        resourceId: i.id,
        resourceName: i.name,
        resourceType: 5,
        resourceMenu: 4
      }))
    },

    async handleNext () {
      try {
        this.nextLoading = true
        await this.$refs['form'].validate()

        this.activeIndex++
      } catch (error) {

      } finally {
        this.nextLoading = false
      }
    },
    handlePrevious () {
      this.activeIndex--
    },
    changeUpload (file, fileList) {
      let reader = new FileReader()
      reader.readAsDataURL(file.raw)
      reader.onload = (event) => {
        const isLt5M = file.size / 1024 / 1024 < 5
        if (!isLt5M) {
          this.$message.error('The size of the uploaded file cannot exceed 5MB!')
          return false
        }
        this.$nextTick(() => {
          this.appInfo.file = event.currentTarget.result
          this.dialogVisible = true
        })
      }
    },
    handleUploadIcon () {
      this.$refs.cropper.getCropData(async (file) => {
        try {
          this.iconLoading = true
          const { postUploadImg } = this.$interface.system
          const params = {
            file,
            path: 'apps',
            bucket: 'bots'
          }
          let { data: response } = await postUploadImg(params)

          if (response.code !== 0) {
            throw get(response, 'msg', '')
          }

          this.appInfo.picture = get(response, 'data.src', '')
          this.dialogVisible = false
        } catch (error) {
          this.$message.error(error)
        } finally {
          this.iconLoading = false
        }
      })
    },
    async init (item) {
      try {
        this.loading = true
        this.appsDialogVisible = true
        if (this.$refs['form']) {
          this.$refs['form'].clearValidate()
        }
        let events = [this.getUserList(), this.getProducts()]
        if (item && item.id) {
          events.push(this.getAppInfo(item.id), this.getVersionList(item.id), this.getSelectList(item.appVersion))
        } else {
          events.push(this.getSelectList('0.0.0'))
        }
        await Promise.all(events)
      } catch (error) {

      } finally {
        this.loading = false
      }
    },
    async getProducts () {
      const params = {
        status: 'active'
      }
      let { data: response } = await this.$interface.pay.productFamilies(params)

      if (response.code !== 0) {
        throw response.msg
      }
      this.products = response.data || []

      return response.data
    },
    async getUserList () {
      const params = {
        datasetKey: 'qwerdsafsadrtfzgsadfggs'
      }
      let { data: response } = await this.$interface.reports.getDrillThroughDataInfo(params)
      if (response.code !== 0) {
        throw response.msg
      }
      this.userList = response.data || []
      return response.data
    },
    async getVersionList (id) {
      const params = {
        appId: id
      }
      let { data: response } = await this.$interface.reports.getVersionListApi(params)
      if (response.code !== 0) {
        throw response.msg
      }
      this.versionHistory = response.data || []

      return response.data
    },
    async getSelectList (version) {
      const params = {
        version
      }
      let { data: response } = await this.$interface.reports.getSelectListApi(params)
      if (response.code !== 0) {
        throw response.msg
      }
      this.versionOptions = response.data || []

      return response.data
    },
    async getAppInfo (id) {
      const params = {
        id
      }
      let { data: response } = await this.$interface.reports.getAppInfoApi(params)
      if (response.code !== 0) {
        throw response.msg
      }

      const { appVersion = '', sysPaywallList = [], appResourceList = [], ...rest } = response.data || {}
      this.appInfo = {
        ...rest,
        sysPaywallList: (sysPaywallList || []).filter(i => i.type !== 11 && i.type !== 12),
        appVersion: (appVersion || '').split('.').map(Number)
      }
      const groupResource = groupBy(appResourceList, 'resourceMenu')
      this.dashboards = groupResource['1'] || []
      this.bots = groupResource['2'] || []
      this.settings = groupResource['3'] || []
      this.widgets = groupResource['4'] || []
      this.datasets = groupResource['5'] || []

      return response.data
    },
    async handleSave () {
      try {
        this.submitLoading = true

        await this.$refs['form'].validate()
        const { id } = this.appInfo

        if (id) {
          await this.update()
        } else {
          await this.doSave()
        }
        this.resetDialog()
        this.$emit('getNewAppsList')
      } catch (error) {
        this.$message.error('Verification failed')
      } finally {
        this.submitLoading = false
      }
    },

    async update () {
      const { putUpdateAppsApi } = this.$interface.reports
      const { appVersion, chargebeeItemPricesList, ...rest } = this.appInfo
      const params = {
        ...rest,
        appVersion: (appVersion || []).join('.'),
        itemId: (chargebeeItemPricesList || []).map(i => i.otherId).join(),
        appResourceList: [...this.dashboards, ...this.bots, ...this.widgets, ...this.settings, ...this.datasets]
      }

      let { data: response } = await putUpdateAppsApi(params)

      if (response.code !== 0) {
        throw get(response, 'msg', '')
      }

      this.$message.success('Update Success')
    },
    async doSave () {
      const { postAddAppsApi } = this.$interface.reports
      const { get } = this._
      const { appVersion = [], chargebeeItemPricesList = [], ...rest } = this.appInfo

      const params = {
        ...rest,
        appVersion: appVersion.join('.'),
        itemId: chargebeeItemPricesList.map(i => i.otherId).join(),
        appResourceList: [...this.dashboards, ...this.bots, ...this.widgets, ...this.settings, ...this.datasets]
      }

      let { data: response } = await postAddAppsApi(params)

      if (response.code !== 0) {
        throw get(response, 'msg', '')
      }

      this.$message.success('Add Success')
    },

    statusHander (item) {
      var temp
      switch (item.status) {
        case 1:
          temp = 'In Dev'
          break
        case 2:
          temp = 'Processing'
          break
        default:
          break
      }
      return temp
    },
    bgchander (item) {
      var temp
      switch (item.status) {
        case 1:
          temp = '#F2F2F2'
          break
        case 2:
          temp = '#FFF7E6'
          break
        default:
          break
      }
      return temp
    },
    colorHander (item) {
      var temp
      switch (item.status) {
        case 1:
          temp = '#0050B3'
          break
        case 2:
          temp = '#FBAB02'
          break
        default:
          break
      }
      return temp
    },

    validatePass (rule, value, callback) {
      var params = {
        id: this.appInfo.id,
        name: this.appInfo.name.trim()
      }
      this.$interface.reports.postValidateNameApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            callback(new Error(res.msg))
          }
          callback()
        }).catch(() => { })
    },
    formatDate (time, str) {
      return GlobalTimeformat(time, 'HH:mm')
    },

    resetDialog () {
      this.appsDialogVisible = false
      this.$emit('falseIsShow')
    },
    clickHandler (index) {
      this.activeIndex = index
    }
  }
}
</script>
<style lang="scss" scoped>
.el-input-number {
  line-height: 32px;
  ::v-deep .el-input-number__decrease {
    line-height: 15px;
  }
  ::v-deep .el-input-number__increase {
    line-height: 15px;
  }
}
.el-date-editor {
  ::v-deep .el-range-separator {
    line-height: 27px;
  }
  ::v-deep .el-range__icon {
    line-height: 27px;
  }
}

.config-rule {
  height: 500px;
  overflow: auto;
}

.cropper-content {
  .cropper {
    width: auto;
    height: 300px;
  }
}
.cursor_pointer {
  cursor: pointer;
}
.bgc_hover:hover {
  background-color: $--theme-color-background;
  color: $--theme-color;
}
.color_hover:hover {
  color: #17b3a3 !important;
}
.dis_flex {
  display: flex;
  height: 670px;
}
.d_left {
  width: 370px;
  height: 100%;
  background-color: #003a8c;
  padding: 70px 28px 32px;
  color: #fff;
}
.d_right {
  width: 590px;
  height: 100%;
  padding: 32px;
  position: relative;
}
::v-deep .el-dialog__header {
  // background-color: #003A8C;
  display: none;
}
::v-deep .el-dialog__body {
  padding: 0;
}
.option_item {
  height: 36px;
  line-height: 36px;
  border-radius: 4px;
  padding-left: 8px;
}
::v-deep .el-table__expanded-cell {
  padding: 10px 40px 0;
  height: 30px;
}
.status {
  height: 20px;
  line-height: 20px;
  border-radius: 10px;
  padding: 0 10px;
}
.input_table {
  height: 32px;
  width: 100px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  text-align: center;
}
.el-form-item {
  margin-bottom: 10px;
}
</style>
